package com.gxc.recursion;

/**
 * 给定一个正方形矩阵，只用有限几个变量，实现矩阵中每个位置的数顺时针转动90度，比如如下的矩阵
 * 0  1  2  3
 * 4  5  6  7
 * 8  9  10 11
 * 12 13 14 15
 * 矩阵应该被调整为:
 * 12 8  4  0
 * 12 9  5  1
 * 14 10 6  2
 * 15 11 7  3
 */
public class Rotate {

    public static void main(String[] args) {
        int[][] array = generate();
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println("");
        }

        rotatePrint(array, 0, 0 , array.length-1, array.length-1);
        System.out.println("-----------");
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println("");
        }
    }

    public static void rotatePrint(int[][] array, int upleftX, int upleftY, int lowRightX, int lowRightY) {
        //边界越过
        if (upleftX > lowRightX || upleftY > lowRightY) return;

        int temp = 0;
        for (int i = 0; i < lowRightY - upleftY; i++) {
            //0->3  3->15  15->12  12->0
            temp = array[upleftX+i][lowRightY];
            array[upleftX+i][lowRightY] = array[upleftX][upleftY+i];
            array[upleftX][upleftY+i] = temp;

            temp = array[lowRightX][lowRightY-i];
            array[lowRightX][lowRightX-i] = array[upleftX][upleftY+i];
            array[upleftX][upleftY+i] = temp;

            temp = array[lowRightX-i][upleftY];
            array[lowRightX-i][upleftY] = array[upleftX][upleftY+i];
            array[upleftX][upleftY+i] = temp;
        }

        rotatePrint(array, upleftX+1 , upleftY+1, lowRightX-1, lowRightY-1);
    }

    private static int[][] generate() {
        int[][] a = new int[7][7];

        int start = 0;
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                a[i][j] = start;
                start++;
            }
        }

        return a;
    }

    public void rotate2(int[][] matrix) {
        int n = matrix.length;
        // 水平翻转
        for (int i = 0; i < n / 2; ++i) {
            for (int j = 0; j < n; ++j) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n - i - 1][j];
                matrix[n - i - 1][j] = temp;
            }
        }
        // 主对角线翻转
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }

}
